import axios from 'axios'
import {useLoginEmpStore} from '@/stores/loginEmp'
const loginEmpStore = useLoginEmpStore();

// import {useRouter} from 'vue-router'
// const router = useRouter();
import router from '@/router/index'
//创建axios实例对象
const request = axios.create({
  baseURL: '/api',
  timeout: 600000
})
//axios的响应 request 拦截器
request.interceptors.request.use(
  (request) => { //把token添加到header
    // 从pinia中获取loginInfo
    const loginInfo = loginEmpStore.getLoginInfo();
    //把token添加到header
    request.headers["token"] = loginInfo?loginInfo.token:'';
    return request;
  },
  (error) => { //失败回调
    return Promise.reject(error)
  }
)

//axios的响应 response 拦截器
request.interceptors.response.use(
  (response) => { //成功回调
    return response.data
  },
  (error) => { //失败回调
    // 说明token为空或者是失效
    if(error.response.status == 401){
      // 跳转登录页
      router.push("/login");
  }
    return Promise.reject(error)
  }
)

export default request